<?php

namespace common\models;

use Yii;
use common\wosotech\Util;
use yii\helpers\Url;
use \yii\helpers\Json;

use common\models\MktFriend;
use common\models\MktFollow;
use common\models\MktGold;
use common\models\MktChat;
use common\models\WxTemplateId;
use common\models\WxGh;

/**
 * This is the model class for table "mkt_user".
 *
 * @property string $id
 * @property string $mobile
 * @property string $email
 * @property string $qq
 * @property string $weixin_number
 * @property string $industry_id
 * @property string $area_id
 * @property string $name
 * @property string $company
 * @property string $duty
 * @property string $password
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $access_token
 * @property string $disabled
 * @property string $status
 * @property string $create_time
 * @property string $update_time
 * @property string $openid
 * @property string $unionid
 * @property integer $subscribe
 * @property integer $subscribe_time
 * @property string $nickname
 * @property integer $sex
 * @property string $city
 * @property string $country
 * @property string $province
 * @property string $headimgurl
 * @property integer $on_message_post
 * @property integer $on_message_friend
 * @property integer $on_message_friend_log
 * @property integer $on_message_system
 * @property integer $on_quiet
 * @property string $on_quiet_start_time
 * @property string $on_quiet_end_time
 * @property integer $on_show_mobile
 * @property integer $on_show_qq
 * @property integer $on_show_weixin
 * @property integer $on_show_email
 */
class MktUser extends \common\wosotech\base\ActiveRecord
{
    const STATUS_GUEST = 0;
    const STATUS_SUBSCRIBER = 1;
    const STATUS_BIND = 2;
    const STATUS_BASE_INFO = 3;
    const STATUS_PART_INFO = 4;
    const STATUS_FULLINFO = 9;

    public $parent_industry_id;
    public $parent_area_id;    

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'mkt_user';
    }

    public function behaviors() {
        return [
            [
                'class' => \yii\behaviors\TimestampBehavior::className(),
                'createdAtAttribute' => 'create_time',
                'updatedAtAttribute' => 'update_time',
                'value' => new \yii\db\Expression('NOW()'),
            ],
        ];
    }

    public function getGh()
    {
        return $this->hasOne(WxGh::className(), ['gh_id' => 'gh_id']);
    }

    public function getIndustry()
    {
        return $this->hasOne(MktIndustry::className(), ['id' => 'industry_id']);
    }
    
    public function getArea()
    {
        return $this->hasOne(MktArea::className(), ['id' => 'area_id']);
    }

    public function getIndustryPaths()
    {
        return empty($this->industry) ? '' : $this->industry->getPaths();
    }

    public function getAreaPaths()
    {
        return empty($this->area) ? '' : $this->area->getPaths();
    }

    public function getGolds() 
    {
        return $this->hasMany(MktGold::className(), [
            'user_id' => 'id',
        ]);
    }

    public function getGoldSum() 
    {
        return $this->hasMany(MktGold::className(), [
            'user_id' => 'id',
        ])->sum('amount');
    }

    public function getGoldSumBySource($source) 
    {
        return $this->hasMany(MktGold::className(), [
            'user_id' => 'id',            
        ])->where(['source' => $source])->sum('amount');
    }

    public function getUsedGoldSum() 
    {
        return $this->hasMany(MktGold::className(), [
            'user_id' => 'id',            
        ])->where('amount < 0')->sum('amount');
    }

    public function getSendChatCount()
    {
        return $this->hasMany(MktChat::className(), ['sender_id' => 'id'])->count();
    }

    public function getRecvChatCount()
    {
        return $this->hasMany(MktChat::className(), ['recver_id' => 'id'])->count();
    }

    // 未读的聊天数
    public function getUnreadRecvChatCount($sender_id = null)
    {
        if (null === $sender_id) {
            return $this->hasMany(MktChat::className(), ['recver_id' => 'id'])->where(['cat' => MktChat::CAT_FRIEND_MESSAGE, 'is_read' => 0, 'is_deleted' => 0])->count();
        } else {
            return $this->hasMany(MktChat::className(), ['recver_id' => 'id'])->where(['sender_id' => $sender_id, 'cat' => MktChat::CAT_FRIEND_MESSAGE, 'is_read' => 0, 'is_deleted' => 0])->count();        
        }
    }

    // 未读的系统发来的聊天数
    //getUnreadSystemRecvChatCount(Yii::$app->keyStorage->get('business.system_sender_id', 2))
    public function getUnreadSystemRecvChatCount($sender_id = null)
    {
        if (null === $sender_id) {
            return $this->hasMany(MktChat::className(), ['recver_id' => 'id'])->where(['cat' => MktChat::CAT_SYSTEM_MESSAGE, 'is_read' => 0, 'is_deleted' => 0])->count();
        } else {
            return $this->hasMany(MktChat::className(), ['recver_id' => 'id'])->where(['sender_id' => $sender_id, 'cat' => MktChat::CAT_SYSTEM_MESSAGE, 'is_read' => 0, 'is_deleted' => 0])->count();        
        }
    }

    // 未读的加好友请求数
    public function getWaitingAddFriendChatCount()
    {
        return $this->hasMany(MktChat::className(), ['recver_id' => 'id'])->where(['cat' => MktChat::CAT_ADD_FRIEND, 'approved' => MktChat::APPROVE_STATUS_WAIT, 'is_deleted' => 0])->count();
    }

    // 关注某人
    public function follow($follow_id) 
    {
        $follow_ids = $this->getFollowIds();
        if (in_array($follow_id, $follow_ids)) return;
        $follow = new MktFollow();
        $follow->user_id = $this->id;
        $follow->follow_id = $follow_id;
        return $follow->save(false);
    }
    public function unFollow($follow_id)
    {
        $model = MktFollow::findOne(['user_id' => $this->id, 'follow_id' => $follow_id]);
        if (null !== $model) {
            return $model->delete();
        }
        return true;
    }

    public function getFollowUsers() 
    {    
        return $this->hasMany(MktUser::className(), ['id' => 'follow_id'])->viaTable(MktFollow::tableName(), ['user_id' => 'id']);  
    }

    public function getFollowCount() 
    {
        return $this->hasMany(MktFollow::className(), ['user_id' => 'id'])->count();
    }

    public function getFollowIds() 
    {
        $follow_ids = MktFollow::find()
            ->select(['follow_id'])
            ->where(['user_id' => $this->id])
            ->column();   
        return $follow_ids;
    }

    public function getFriendUsers() 
    {    
        return $this->hasMany(MktUser::className(), ['id' => 'friend_id'])->viaTable(MktFriend::tableName(), ['user_id' => 'id']);  
    }

    public function getFriendCount() 
    {
        return $this->hasMany(MktFriend::className(), ['user_id' => 'id'])->count();
    }

    public function getFriendIds() 
    {
        $friend_ids = MktFriend::find()
            ->select(['friend_id'])
            ->where(['user_id' => $this->id])
            ->column();   
        return $friend_ids;
    }

    public function getTheName() 
    {
        return $this->name;
    }

    public function getTheHeadimgurl() 
    {
        return $this->headimgurl;
    }

    public function getScreenMobile($me) 
    {
        //yii::error("$me->id, $this->id");
        if ($me->isMyFriend($this->id)) {
            return $this->on_show_mobile ? $this->mobile : '***';
        } else {
            return $this->on_show_mobile ? '好友可见' : '不可见';        
        }
    }

    public function getScreenQq($me) 
    {
        if ($me->isMyFriend($this->id)) {
            return $this->on_show_qq ? $this->qq : '***';
        } else {
            return $this->on_show_qq ? '好友可见' : '不可见';        
        }
    }
    
    public function getScreenWeixin($me) 
    {
        if ($me->isMyFriend($this->id)) {
            return $this->on_show_weixin ? $this->weixin_number : '***';
        } else {
            return $this->on_show_weixin ? '好友可见' : '不可见';        
        }
    }
    
    public function getScreenEmail($me) 
    {
        if ($me->isMyFriend($this->id)) {
            return $this->on_show_email ? $this->email : '***';
        } else {
            return $this->on_show_email ? '好友可见' : '不可见';        
        }
    }

    public function getPosts() 
    {
        return $this->hasMany(MktPost::className(), ['user_id' => 'id']);
    }

    public function getPostCount() 
    {
        return $this->hasMany(MktPost::className(), ['user_id' => 'id'])->where(['status' => MktPost::POST_STATUS_NORMAL])->count();
    }

    public function getAllPostCount() 
    {
        return $this->hasMany(MktPost::className(), ['user_id' => 'id'])->count();
    }

    public function getPostCountToday() 
    {
        return $this->hasMany(MktPost::className(), ['user_id' => 'id'])->today()->count();
    }

    // 我对别人贴子的响应
    public function getPostResponses() 
    {
        return $this->hasMany(MktPostResponse::className(), ['user_id' => 'id']);
    }

    public function getPostResponseCount() 
    {
        return $this->hasMany(MktPostResponse::className(), ['user_id' => 'id'])->count();
    }

    public function getPostResponseCountToday() 
    {
        return $this->hasMany(MktPostResponse::className(), ['user_id' => 'id'])->today()->count();
    }

    // 别人对我贴子的响应
    public function getReceivedPostResponses() 
    {
       return $this->hasMany(MktPostResponse::className(), ['post_id' => 'id'])->viaTable(MktPost::tableName(), ['user_id' => 'id']);          
    }

    // 未处理的别人对我贴子的响应数
    public function getReceivedPostResponseCount() 
    {
/*
        $receivedPostResponsesCount = MktUser::find()
            ->joinWith('receivedPostResponses')
            ->andWhere([
                'mkt_post.user_id' => $me->id,
                'is_done' => 0
            ])
            ->andFilterWhere(['mkt_post.status' => MktPost::POST_STATUS_NORMAL])
            ->count();
*/
       return MktPostResponse::find()
            ->joinWith('post')
            ->andWhere([
                'mkt_post.user_id' => $this->id,
                'is_done' => 0
            ])
            ->andFilterWhere(['mkt_post.status' => MktPost::POST_STATUS_NORMAL])
            ->count();       
    }
      
    public function getSourceCount()
    {
        return $this->sourceRoomCount + $this->sourceMemberCount + $this->sourceGiftCount
            + $this->sourcePromotionCount + $this->sourceDonateCount + $this->sourceServiceCount;
    }

    public function getSourceRooms() 
    {    
        return $this->hasMany(MktSourceRoom::className(), ['user_id' => 'id']);
    }

    public function getSourceRoomCount() 
    {
        return $this->hasMany(MktSourceRoom::className(), ['user_id' => 'id'])->count();
    }

    public function getSourceMembers() 
    {    
        return $this->hasMany(MktSourceMember::className(), ['user_id' => 'id']);
    }

    public function getSourceMemberCount() 
    {
        return $this->hasMany(MktSourceMember::className(), ['user_id' => 'id'])->count();
    }

    public function getSourceGifts() 
    {    
        return $this->hasMany(MktSourceGift::className(), ['user_id' => 'id']);
    }

    public function getSourceGiftCount() 
    {
        return $this->hasMany(MktSourceGift::className(), ['user_id' => 'id'])->count();
    }

    public function getSourcePromotions() 
    {    
        return $this->hasMany(MktSourcePromotion::className(), ['user_id' => 'id']);
    }

    public function getSourcePromotionCount() 
    {
        return $this->hasMany(MktSourcePromotion::className(), ['user_id' => 'id'])->count();
    }

    public function getSourceDonates() 
    {    
        return $this->hasMany(MktSourceDonate::className(), ['user_id' => 'id']);
    }

    public function getSourceDonateCount() 
    {
        return $this->hasMany(MktSourceDonate::className(), ['user_id' => 'id'])->count();
    }

    public function getSourceServices() 
    {    
        return $this->hasMany(MktSourceService::className(), ['user_id' => 'id']);
    }

    public function getSourceServiceCount() 
    {
        return $this->hasMany(MktSourceService::className(), ['user_id' => 'id'])->count();
    }

    static function getStatusOptions($key = null) 
    {
        $arr = array(
            self::STATUS_GUEST => '游客',
            self::STATUS_SUBSCRIBER => '已关注',
            self::STATUS_BIND => '已绑定手机',
            self::STATUS_BASE_INFO => '基本信息',
            self::STATUS_PART_INFO => '未补全',
            self::STATUS_FULLINFO => '已补全',            
        );        
        return $key === null ? $arr : (isset($arr[$key]) ? $arr[$key] : '');
    }
    
/*
    public function afterFind()
    {
        if (!empty($this->industry->parent)) {
            $this->parent_industry_id = $this->industry->parent->id;
        }
        if (!empty($this->area_id)) {
            $this->parent_area_id = $this->area->parent->id;
        }
        parent::afterFind();
    }
*/ 

    public function beforeSave($insert) {
        //$oldStatus = $this->status;             
        $this->mobile = ('' == $this->mobile) ? NULL : $this->mobile;
        $this->email = ('' == $this->email) ? NULL : $this->email;
        $this->qq = ('' == $this->qq) ? NULL : $this->qq;
        $this->weixin_number = ('' == $this->weixin_number) ? NULL : $this->weixin_number;
        $this->openid = ('' == $this->openid) ? NULL : $this->openid;      

        if (!$this->subscribe) {
            $this->status = self::STATUS_GUEST;
        } else if (empty($this->mobile)) {
            $this->status = self::STATUS_SUBSCRIBER;
        } else if (empty($this->name)) {
            $this->status = self::STATUS_BIND;
        } else if (empty($this->email) && empty($this->qq) && empty($this->weixin_number) ) {
            $this->status = self::STATUS_BASE_INFO;
        } else if (!empty($this->email) && !empty($this->qq) && !empty($this->weixin_number) ) {
            $this->status = self::STATUS_FULLINFO;
        } else {
            $this->status = self::STATUS_PART_INFO;
        }

        return parent::beforeSave($insert);
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);        
        if ($insert) return;
        //yii::error(print_r($changedAttributes, true));                    
        //if (empty($changedAttributes['mobile']) && !empty($this->mobile)) {
        //}            
        // if ($changedAttributes['status'] == self::STATUS_SUBSCRIBER && $this->status == self::STATUS_BIND ) {
            //$this->addGold(Yii::$app->keyStorage->get('business.golds_bind_mobile', 10), MktGold::SOURCE_REASON_BIND_MOBILE, "绑定手机赠送积分");
        //}
        if (isset($changedAttributes['status'])) 
        {
            $oldStatus = $changedAttributes['status']; 
            
            if ($oldStatus != self::STATUS_BIND && $this->status == self::STATUS_BIND) {
                if (MktGold::findOne(['user_id' => $this->id, 'source' => MktGold::SOURCE_REASON_BIND_MOBILE]) === null) {
                    //yii::error('ready to send money for bind mobile');
                    $this->addGold(Yii::$app->keyStorage->get('business.golds_bind_mobile', 10), MktGold::SOURCE_REASON_BIND_MOBILE, "绑定手机赠送积分");            
                } else {
                    //yii::error('Already sent money for bind mobile!');
                }
            }

            if ($oldStatus != self::STATUS_FULLINFO && $this->status == self::STATUS_FULLINFO) {
                if (MktGold::findOne(['user_id' => $this->id, 'source' => MktGold::SOURCE_REASON_FULL_INFO]) === null) {
                    //yii::error('ready to send money for full info');
                    $this->addGold(Yii::$app->keyStorage->get('business.golds_full_info', 30), MktGold::SOURCE_REASON_FULL_INFO, "补全信息赠送积分");            
                } else {
                    //yii::error('Already sent money for full info!');
                }
            }
        }
        
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['industry_id', 'area_id', 'disabled', 'status', 'subscribe', 'subscribe_time', 'sex', 'on_message_post', 'on_message_friend', 'on_message_friend_log', 'on_message_system', 'on_quiet', 'on_show_mobile', 'on_show_qq', 'on_show_weixin', 'on_show_email'], 'integer'],
            [['create_time', 'update_time', 'on_quiet_start_time', 'on_quiet_end_time'], 'safe'],
            [['mobile', 'name'], 'string', 'max' => 32],
            [['email', 'qq', 'weixin_number', 'password', 'auth_key', 'password_hash', 'password_reset_token', 'access_token', 'openid', 'unionid', 'city', 'country', 'province'], 'string', 'max' => 64],
            [['company', 'duty'], 'string', 'max' => 128],
            [['nickname', 'headimgurl'], 'string', 'max' => 255],
            [['mobile'], 'unique'],
            [['email'], 'unique'],
            [['qq'], 'unique'],
            [['weixin_number'], 'unique'],
            [['openid'], 'unique'],
            
            [['parent_industry_id', 'parent_area_id'], 'safe'],            
            
        ];
    }
    
    public static function findByOpenid($openid)
    {
        return self::findOne(['openid' => $openid]);
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'mobile' => '手机号',
            'email' => '邮箱',
            'qq' => 'QQ',
            'weixin_number' => '微信号',
            'industry_id' => '行业ID',
            'area_id' => '区域ID',
            'name' => '姓名',
            'company' => '机构',
            'duty' => '职务',
            'password' => '明文密码',
            'auth_key' => 'Auth Key',
            'password_hash' => '密码',
            'password_reset_token' => 'Password Reset Token',
            'access_token' => 'Access Token',
            'disabled' => '禁用',
            'status' => '状态',
            'create_time' => '创建时间',
            'update_time' => '修改时间',
            'openid' => 'OpenID',
            'unionid' => 'Unionid',
            'subscribe' => '已关注',
            'subscribe_time' => '关注时间',
            'nickname' => '微信昵称',
            'sex' => '性别',
            'city' => '市',
            'country' => '国家',
            'province' => '省',
            'headimgurl' => '微信头像',
            'on_message_post' => '贴子消息',
            'on_message_friend' => '好友消息',
            'on_message_friend_log' => '申请好友消息',
            'on_message_system' => '系统消息',
            'on_quiet' => '勿扰模式',
            'on_quiet_start_time' => '拒收起始时间',
            'on_quiet_end_time' => '拒收结束时间',
            'on_show_mobile' => '对好友显示手机',
            'on_show_qq' => '对好友显示qq',
            'on_show_weixin' => '对好友显示微信',
            'on_show_email' => '对好友显示邮箱',
        ];
    }

    /**
     * @inheritdoc
     * @return MktUserQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new MktUserQuery(get_called_class());
    }

    public static function getLatestUsersAjax($params)
    {
        yii::error(print_r([$_GET, $params], true));
        $searchModel = new MktUserSearch();
        $dataProvider = $searchModel->searchWap($_GET, MktUser::find()->select(['id', 'name', 'headimgurl','nickname', 'sex', 'company', 'duty'])->wapMarketListMethod()->asArray());
        $data = $dataProvider->getModels();
        yii::error(print_r($data, true));
        return \yii\helpers\Json::encode(['code' => 0, 'data' => $data]);
    }

    public function isWoman()
    {
        return $this->sex ? false : true;
    }

    public function isMyFriend($id)
    {
        return null === MktFriend::findOne(['user_id' => $this->id, 'friend_id' => $id]) ? false : true;
    }

    public function isMyFollow($id)
    {
        return null === MktFollow::findOne(['user_id' => $this->id, 'follow_id' => $id]) ? false : true;
    }

    public function isMyCollect($id)
    {
        return null === MktCollect::findOne(['user_id' => $this->id, 'post_id' => $id]) ? false : true;
    }

    public function getCollectIds() 
    {
        $post_ids = MktCollect::find()
            ->select(['post_id'])
            ->where(['user_id' => $this->id])
            ->column();   
        return $post_ids;
    }

    public function collect($post_id) 
    {
        $post_ids = $this->getCollectIds();
        if (in_array($post_id, $post_ids)) return true;
        $collect = new MktCollect();
        $collect->user_id = $this->id;
        $collect->post_id = $post_id;
        return $collect->save(false);
    }
    public function unCollect($post_id)
    {
        $model = MktCollect::findOne(['user_id' => $this->id, 'post_id' => $post_id]);
        if (null !== $model) {
            return $model->delete();
        }
        return true;
    }

    // 申请加好, 扣金币, 发消息给对方, 等待对方同意
    public function applyAddFriend($friend_id)
    {
        $friend_ids = $this->getFriendIds();
        if (in_array($friend_id, $friend_ids)) {
            return 'You already are friends';
        }
        if ($this->getGoldSum() < Yii::$app->keyStorage->get('business.golds_per_friend', 10)) {
            return '金币不足啦!';
        }
        $model = MktUser::findOne($friend_id);
        $this->addGold(-Yii::$app->keyStorage->get('business.golds_per_friend', 10), MktGold::SOURCE_REASON_APPLY_FRIEND, "向{$model->name}申请加好友");
        $this->sendMessage($friend_id);
        return true;
    }

    public function sendMessage($friend_id)
    {
        $chat = new MktChat();
        $chat->cat = MktChat::CAT_ADD_FRIEND;
        $chat->sender_id = $this->id;
        $chat->recver_id = $friend_id;
        $chat->content = 'Apply friend';
        return $chat->save();
    }

    // 同意某人的加好友请求, A加B为好友,则B也是A的好友. 同时把相互的收藏关系删掉?
    public function allowFriend($friend_id)
    {
        $friend_ids = $this->getFriendIds();
        if (in_array($friend_id, $friend_ids)) return true;
        $friend = new MktFriend();
        $friend->user_id = $this->id;
        $friend->friend_id = $friend_id;
        if ($friend->save(false)) {
            $friend = new MktFriend();
            $friend->user_id = $friend_id;
            $friend->friend_id = $this->id;
            return $friend->save(false);
        }
        return false;
    }

    public function addGold($amount, $source = 0, $memo = '')
    {
        $gold = new MktGold();
        $gold->user_id = $this->id;
        $gold->amount = $amount;
        $gold->memo = $memo;
        $gold->source = $source;
        return $gold->save();
    }

    public static function toggleCollectAjax($params)
    {
        yii::error(print_r([$_GET, $params], true));
        $user_id = $params['user_id'];
        $post_id = $params['post_id'];
        $me = MktUser::findOne($params['user_id']);
        if ($me->isMyCollect($post_id)) {
            $me->unCollect($post_id);
        } else {
            $me->collect($post_id);
        }
        return \yii\helpers\Json::encode(['code' => 0, 'data' => 'OK']);
    }

    public static function toggleFollowAjax($params)
    {
        yii::error(print_r([$_GET, $params], true));
        $user_id = $params['user_id'];
        $follow_id = $params['follow_id'];
        $me = MktUser::findOne($params['user_id']);
        if ($me->isMyFollow($follow_id)) {
            $me->unFollow($follow_id);
        } else {
            $me->follow($follow_id);
        }
        return \yii\helpers\Json::encode(['code' => 0, 'data' => 'OK']);
    }

    public static function deleteFriendAjax($params)
    {
        yii::error(print_r([$_GET, $params], true));
        $user_id = $params['user_id'];
        $friend_id = $params['friend_id'];
        
        $friend = MktFriend::findOne(['user_id'=>$user_id, 'friend_id'=>$friend_id]);
        if (null !== $friend) $friend->delete();
        $friend = MktFriend::findOne(['user_id'=>$friend_id, 'friend_id'=>$user_id]);
        if (null !== $friend) $friend->delete();

        $n = MktChat::updateAll(['is_deleted' => 1], '(sender_id = :sender_id AND recver_id = :recver_id) OR (sender_id = :recver_id AND recver_id = :sender_id)', [':sender_id' => $user_id, ':recver_id' => $friend_id]);

        return \yii\helpers\Json::encode(['code' => 0, 'msg' => 'OK']);
    }

    public static function addFriendAjax($params)
    {
        yii::error(print_r([$_GET, $params], true));
        $user_id = $params['user_id'];
        $friend_id = $params['friend_id'];
        $me = MktUser::findOne($params['user_id']);

        $result = $me->applyAddFriend($friend_id);
        if ( true !== $result) {
            yii::error($result);
            return \yii\helpers\Json::encode(['code' => 1, 'data' => $result]);
        }
        return \yii\helpers\Json::encode(['code' => 0, 'data' => 'OK']);
    }

    public static function bindMobileAjax($params)
    {
        $verifycode_cache = \Yii::$app->cache->get('SMS-VERIFY-CODE' . $params['mobile']);
        if (empty($verifycode_cache)) {
            return \yii\helpers\Json::encode(['code' => -1, 'msg' => '验证码失效！']);
        }
        elseif ($verifycode_cache !== $params['verifycode']) {
            return \yii\helpers\Json::encode(['code' => -2, 'msg' => '验证码错误！']);
        }

        if (null !== MktUser::findOne(['mobile' => $params['mobile']])) {
            return \yii\helpers\Json::encode(['code' => 1, 'msg' => '此手机号已被使用!']);        
        }
        
        $model = MktUser::findOne(['openid' => $params['openid']]);
        $model->mobile = $params['mobile'];        
        $result = $model->save();
        if ( true !== $result) {
            yii::error(print_r($model->getErrors(), true));
            return \yii\helpers\Json::encode(['code' => 1, 'msg' => '保存错误']);
        }
        return \yii\helpers\Json::encode(['code' => 0, 'msg' => 'OK']);
    }

    public static function modifyNameAjax($params)
    {
        $model = MktUser::findOne($params['id']);
        $model->name = $params['name'];        
        if ($model->save()) {
            return \yii\helpers\Json::encode(['code' => 0, 'data' => 'OK']);
        }
        yii::error(print_r($model->getErrors(), true));
        return \yii\helpers\Json::encode(['code' => 1, 'data' => '保存错误']);        
    }

    public static function modifyCompanyAjax($params)
    {
        $model = MktUser::findOne($params['id']);
        $model->company = $params['company'];        
        if ($model->save()) {
            return \yii\helpers\Json::encode(['code' => 0, 'data' => 'OK']);
        }
        yii::error(print_r($model->getErrors(), true));
        return \yii\helpers\Json::encode(['code' => 1, 'data' => '保存错误']);        
    }

    public static function modifyEmailAjax($params)
    {
        $model = MktUser::findOne($params['id']);
        $model->email = $params['email'];        
        if ($model->save()) {
            return \yii\helpers\Json::encode(['code' => 0, 'data' => 'OK']);
        }
        yii::error(print_r($model->getErrors(), true));
        return \yii\helpers\Json::encode(['code' => 1, 'data' => '保存错误']);        
    }

    public static function modifyIndustryAjax($params)
    {
        $model = MktUser::findOne($params['id']);
        $model->industry_id = $params['industry_id'];        
        if ($model->save()) {
            return \yii\helpers\Json::encode(['code' => 0, 'data' => 'OK']);
        }
        yii::error(print_r($model->getErrors(), true));
        return \yii\helpers\Json::encode(['code' => 1, 'data' => '保存错误']);        
    }

    public static function modifyAreaAjax($params)
    {
        $model = MktUser::findOne($params['id']);
        $model->area_id = $params['area_id'];        
        if ($model->save()) {
            return \yii\helpers\Json::encode(['code' => 0, 'data' => 'OK']);
        }
        yii::error(print_r($model->getErrors(), true));
        return \yii\helpers\Json::encode(['code' => 1, 'data' => '保存错误']);        
    }

    public static function modifyQqAjax($params)
    {
        $model = MktUser::findOne($params['id']);
        $model->qq = $params['qq'];        
        if ($model->save()) {
            return \yii\helpers\Json::encode(['code' => 0, 'data' => 'OK']);
        }
        yii::error(print_r($model->getErrors(), true));
        return \yii\helpers\Json::encode(['code' => 1, 'data' => '保存错误']);        
    }

    public static function modifyMobileAjax($params)
    {
        $model = MktUser::findOne($params['id']);
        $model->mobile = $params['mobile'];        
        if ($model->save()) {
            return \yii\helpers\Json::encode(['code' => 0, 'data' => 'OK']);
        }
        yii::error(print_r($model->getErrors(), true));
        return \yii\helpers\Json::encode(['code' => 1, 'data' => '保存错误']);        
    }

    public static function modifyWeixinAjax($params)
    {
        $model = MktUser::findOne($params['id']);
        $model->weixin_number = $params['weixin_number'];        
        if ($model->save()) {
            return \yii\helpers\Json::encode(['code' => 0, 'data' => 'OK']);
        }
        yii::error(print_r($model->getErrors(), true));
        return \yii\helpers\Json::encode(['code' => 1, 'data' => '保存错误']);        
    }

    public static function modifyDutyAjax($params)
    {
        $model = MktUser::findOne($params['id']);
        $model->duty = $params['duty'];        
        if ($model->save()) {
            return \yii\helpers\Json::encode(['code' => 0, 'data' => 'OK']);
        }
        yii::error(print_r($model->getErrors(), true));
        return \yii\helpers\Json::encode(['code' => 1, 'data' => '保存错误']);        
    }

    public static function modifySexAjax($params)
    {
        $model = MktUser::findOne($params['id']);
        $model->sex = $params['sex'];        
        if ($model->save()) {
            return \yii\helpers\Json::encode(['code' => 0, 'data' => 'OK']);
        }
        yii::error(print_r($model->getErrors(), true));
        return \yii\helpers\Json::encode(['code' => 1, 'data' => '保存错误']);        
    }

    public static function toggleAjax($params)
    {
        $model = MktUser::findOne($params['id']);
        $model->$params['field'] = $model->$params['field'] ? 0 : 1;        
        if (in_array($params['field'], ['on_show_mobile', 'on_show_qq', 'on_show_weixin', 'on_show_email'])) {
            if (  0 == $model->on_show_mobile + $model->on_show_qq + $model->on_show_weixin + $model->on_show_email) {
                return \yii\helpers\Json::encode(['code' => 1, 'msg' => '必须至少提供一种联系方式!']);                        
            }
        }
        if ($model->save()) {
            return \yii\helpers\Json::encode(['code' => 0, 'msg' => 'OK']);
        }
        yii::error(print_r($model->getErrors(), true));
        return \yii\helpers\Json::encode(['code' => 1, 'msg' => '保存错误']);        
    }

    public static function updateAttributeAjax($params)
    {
        $model = MktUser::findOne($params['id']);
        $attribute = $params['attribute'];        
        $model->$attribute = $params['value'];        
        if ($model->save()) {
            return \yii\helpers\Json::encode(['code' => 0, 'data' => 'OK']);
        }
        yii::error(print_r($model->getErrors(), true));
        return \yii\helpers\Json::encode(['code' => 1, 'data' => '保存错误']);        
    }

    public function getJump()
    {    
            if (empty($this->mobile)) 
            {
                 return Url::to(['wap/bindphone']);
            }

            if (empty($this->name) || empty($this->company) || empty($this->duty) || empty($this->industry_id) || empty($this->area_id)) 
            {
                 return Url::to(['wap/bind-corp']);                
            }             
            return '';
    }

    public function sendTemplateMsgRegisterMember($url='') 
    {
        $wxapp =  $this->gh->loadWx(false)->getApplication();        
        $remark = '';
        $remark .= '机构：' . $this->company . PHP_EOL;
        $remark .= '职务：' . $this->duty . PHP_EOL;
        $remark .= '行业：' . $this->industryPaths . PHP_EOL;     
        $remark .= PHP_EOL;             
        $remark .= '谢谢您对聚用网的支持！';
                
        $data = [
            'first' => [
                'value' => $this->name . "您好，恭喜您！"  . PHP_EOL . "聚用网会员注册成功！注册信息如下：",
                'color' => '#173177',
            ],
            'cardNumber' => [
                'value' => $this->id,
                'color' => '#173177',
            ],
            'type' => [
                'value' => '',
                'color' => '#173177',
            ],
            'address' => [
                'value' => $this->areaPaths,
                'color' => '#173177',
            ],
            'VIPName' => [
                'value' => $this->name,
                'color' => '#173177',
            ],
            'VIPPhone' => [
                'value' => $this->mobile,
                'color' => '#173177',
            ],
            'expDate' => [
                'value' => date('Y年m月d日'),
                'color' => '#173177',
            ],
            'remark' => [
                'value' => $remark,
                'color' => '#173177',
            ],
        ];

        $responseArray = $wxapp->notice->send([
            'touser' => $this->openid,
            'template_id' => $this->gh->getTemplateId(WxTemplateId::TEMPLATE_ID_SHORT_REGISTER_MEMBER),
            'url' => $url,
            'topcolor' => '',
            'data' => $data,
        ]);
/*        
        Array
        (
            [errcode] => 0
            [errmsg] => ok
            [msgid] => 435747134
        )
        yii::error(print_r($responseArray, true));
*/        
    }

    static public function adjustGoldBalance() 
    {
        //\Yii::$app->db->createCommand("UPDATE mkt_user SET points = :point")->bindValues([':point' => 50])->execute();
        foreach (MktUser::find()->where([])->each(100) as $model) {
            if (($sum = $model->getGoldSum()) < 50) {
                //yii::warning($model->id);
                $model->addGold(50 - $sum, MktGold::SOURCE_REASON_SYSTEM_AUTO_SEND_MONEY, "系统自动赠送");                
            }
        }     
    }
}

